﻿using AutoMapper;
using MediatR;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.ErrorCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.RBAC.API.Application.Common.Role
{
    /// <summary>
    /// 角色添加Handler
    /// </summary>
    public class CreateRolesHandler : IRequestHandler<CreateRolesCommand, Result>
    {
        /// <summary>
        /// mapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 角色表仓储
        /// </summary>
        public readonly IBaseRepository<Roles> rolesrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CreateRolesHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper">mapper</param>
        /// <param name="rolesrepository">rolesrepository</param>
        /// <param name="logger">logger</param>
        public CreateRolesHandler(IMapper mapper, IBaseRepository<Roles> rolesrepository, ILogger<CreateRolesHandler> logger)
        {
            this.mapper = mapper;
            this.rolesrepository = rolesrepository;
            this.logger = logger;
        }
        /// <summary>
        /// 角色添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(CreateRolesCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                Roles roles = mapper.Map<Roles>(request);
                var res = await rolesrepository.Add(roles);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "角色添加成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "角色添加失败" + ex.Message;
                logger.LogError("角色添加失败" + ex.Message);
            }
            return result;
        }
    }
}
